package com.imist.connectpool;

import com.imist.jdbcutil.JDBCUtil;
import com.imist.jdbcutil.JDBCUtil2;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class DataSourceDemo1 {

    /**
     * xml配置文件设置连接池
     */
    @Test
    public void demo2(){
        Connection conn = null;
        PreparedStatement preparedStatement= null;
        ResultSet resultSet = null;
        try{
            //创建连接池，自动加载c3p0-config.xml的参数
            //ComboPooledDataSource dataSource = new ComboPooledDataSource();
            conn = JDBCUtil2.getConnection();
            String sql = "SELECT  * FROM user";
            preparedStatement = conn.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                System.out.println(resultSet.getString("username") +"   " + resultSet.getString("password")+"    " +resultSet.getString("name"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil2.release(conn,preparedStatement,resultSet);
        }
    }

    /**
     * 手动设置连接池
     */
    @Test
    public void demo1(){
        Connection conn = null;
        PreparedStatement preparedStatement= null;
        ResultSet resultSet = null;
        try{
            //创建连接池
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            //设置连接池参数
            dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/jdbc_test?useSSL=false&characterEncoding=UTF-8");
            dataSource.setUser("root");
            dataSource.setPassword("123456");
            dataSource.setMaxPoolSize(20);
            dataSource.setInitialPoolSize(3);

            conn = dataSource.getConnection();
            String sql = "SELECT  * FROM user";
            preparedStatement = conn.prepareStatement(sql);
            resultSet = preparedStatement.executeQuery();
            while (resultSet.next()){
                System.out.println(resultSet.getString("username") +"   " + resultSet.getString("password")+"    " +resultSet.getString("name"));
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.release(conn,preparedStatement,resultSet);
        }
    }
}
